package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.OrderBean;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SetmealService setmealService;

    @Override
    public Result findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Order> page = orderMapper.selectByCondition(queryPageBean.getQueryString());
        List<Order> orderList = page.getResult();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (Order order : orderList) {
            String s = sdf.format(order.getOrderDate());
            order.setDate(s);
            order.setSetmealName(setmealMapper.findById(order.getSetmealId()).getName());
            order.setFileNumber(orderMapper.findMemberById(order.getMemberId()).getFileNumber());
            order.setMemberName(orderMapper.findMemberById(order.getMemberId()).getName());
            order.setMemberSex(orderMapper.findMemberById(order.getMemberId()).getSex());
            order.setMemberPhoneNumber(orderMapper.findMemberById(order.getMemberId()).getPhoneNumber());
        }

        PageResult pageResult = new PageResult(page.getTotal(), orderList);
        return Result.success(MessageConstant.QUERY_ORDER_SUCCESS, pageResult);
    }

    @Override
    public Result deleteById(Integer id) {
        Date date = orderMapper.findDateById(id);
        orderMapper.deleteById(id);
        orderSettingMapper.updateReservationsByDate(date, -1);
        return Result.success("删除成功", null);
    }

    @Override
    public Result submitOrder(OrderBean orderBean) {
        //检查当前日期是否进行了预约设置
        OrderSetting orderSetting = orderSettingMapper.findOrderSettingByOrderDate(orderBean.getOrderDate());
        if (orderSetting == null) {
            return Result.fail(MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //检查预约日期是否预约已满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return Result.fail(MessageConstant.ORDER_FULL);
        }
        //检查当前用户是否为会员，根据手机号判断
        Member member = memberMapper.findByPhone(orderBean.getTelephone());
        //防止重复预约
        if (member != null) {
            Order order = orderMapper.findOrder(member.getId(), orderBean.getOrderDate(), orderBean.getSetmealId());
            if (order != null) {
                return Result.fail(MessageConstant.HAS_ORDERED);
            }
        }

        //当前用户不是会员，需要添加到会员表
        if (member == null) {
            member = new Member();
            member.setName(orderBean.getName());
            member.setSex(orderBean.getSex());
            member.setPhoneNumber(orderBean.getTelephone());
            member.setIdCard(orderBean.getIdCard());
            memberMapper.save(member);
        }

        //保存预约信息到预约表
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(orderBean.getOrderDate());
        if (StringUtil.isEmpty(orderBean.getOrderType())) {
            order.setOrderType(Order.ORDERTYPE_WEIXIN);
        } else {
            order.setOrderType(orderBean.getOrderType());
        }
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(orderBean.getSetmealId());
        orderMapper.save(order);

        //预约成功，更新当日的已预约人数
        int oldReservations = orderSetting.getReservations();
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        int count = orderSettingMapper.updateReservations(orderSetting.getId(), orderSetting.getReservations(), oldReservations);

        if (count == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("预约失败,请重试!");
        }
        return Result.success(MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Result findOrderBeanById(Integer orderId) {
        Map map = orderMapper.findById(orderId);
        List<Setmeal> list = (List<Setmeal>) setmealService.findAll().getData();
        if (list == null) {
            return Result.fail(MessageConstant.GET_SETMEAL_LIST_FAIL);
        }
        map.put("setmealList", list);
        return Result.success(MessageConstant.QUERY_ORDER_SUCCESS, map);
    }

    @Override
    public Result updateOrder(OrderBean orderBean) {
        Map map = orderMapper.findById(orderBean.getId());
        Date oldDate = (Date) map.get("orderDate");
        String orderStatus = (String) map.get("orderStatus");
        //检查当前日期是否进行了预约设置
        OrderSetting orderSetting = orderSettingMapper.findOrderSettingByOrderDate(orderBean.getOrderDate());
        if (orderSetting == null) {
            return Result.fail(MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        if (!(oldDate.compareTo(orderBean.getOrderDate())==0)){
            //检查预约日期是否预约已满
            int number = orderSetting.getNumber();
            int reservations = orderSetting.getReservations();
            if (reservations >= number) {
                return Result.fail(MessageConstant.ORDER_FULL);
            }
        }

        if (orderStatus.equals(orderBean.getOrderStatus())){
            //获取当前用户
            Member member = memberMapper.findByPhone(orderBean.getTelephone());
            //防止重复预约
            if (member != null) {
                Order order = orderMapper.findOrder(member.getId(), orderBean.getOrderDate(), orderBean.getSetmealId());
                if (order != null) {
                    return Result.fail(MessageConstant.HAS_ORDERED);
                }
            }
        }

        Order order = new Order();
        order.setId(orderBean.getId());
        order.setOrderDate(orderBean.getOrderDate());
        order.setSetmealId(orderBean.getSetmealId());
        order.setOrderStatus(orderBean.getOrderStatus());

        orderMapper.update(order);

        //预约成功，更新当日的已预约人数
        int oldReservations = orderSetting.getReservations();
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        int count = orderSettingMapper.updateReservations(orderSetting.getId(), orderSetting.getReservations(), oldReservations);

        orderSettingMapper.updateReservationsByDate(oldDate, -1);

        if (count == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("预约失败,请重试!");
        }

        return Result.success("编辑成功", null);
    }

    @Override
    public Result findById(Integer id) {
        Map map = orderMapper.findOrderDetail(id);
        if (map != null) {
            String orderDate = map.get("orderDate").toString();
            map.put("orderDate", orderDate);
        }
        return Result.success(MessageConstant.QUERY_ORDER_SUCCESS, map);
    }

}
